//
//  ViewController.m
//  DDPushTest
//
//  Created by YC on 2017/8/29.
//  Copyright © 2017年 YC. All rights reserved.
//

#import "ViewController.h"
@import CocoaAsyncSocket;

@interface ViewController ()<GCDAsyncSocketDelegate> {
    uuid_t _uuid;
}

@property (strong, nonatomic) GCDAsyncSocket *socket;
@property (strong, nonatomic) NSTimer *connectTimer;
@property (assign, nonatomic) BOOL connected;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSUUID *vendorIdentifier = [[UIDevice currentDevice] identifierForVendor];
    [vendorIdentifier getUUIDBytes:_uuid];
    
    self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self
                                             delegateQueue:dispatch_get_main_queue()];
    
    NSError *error = nil;
    self.connected = [self.socket connectToHost:@"192.168.3.19"
                                         onPort:9999
                                   viaInterface:nil
                                    withTimeout:-1
                                          error:&error];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - GCDAsyncSocketDelegate

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"连接成功");
    [self addTimer];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
    NSLog(@"%s--%ld",__func__,tag);
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
}

- (void)addTimer {
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                         target:self
                                                       selector:@selector(longConnectToSocket)
                                                       userInfo:nil
                                                        repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:self.connectTimer
                                 forMode:NSRunLoopCommonModes];
}

- (void)longConnectToSocket{
    
    NSData *data = [self getHeartbeatPacketDataWithUUID:_uuid];
    [self.socket writeData:data withTimeout:-1 tag:1];
    
    [self sendMessage];
    NSLog(@"心跳");
}

- (void)sendMessage {
    NSString *uuid = @"7b774effe4a349c6dd82ad4f4f21d34c";
    NSData *data = [self get0x20DataWithUUID:uuid];
    [self.socket writeData:data withTimeout:-1 tag:2];
    
}

//心跳包
//命令码：0（0x00）。格式：[1][1][0x00][16字节uuid][0x0000]
- (NSData *)getHeartbeatPacketDataWithUUID:(uuid_t)UUID {
    Byte bytes[21];
    
    bytes[0] = 0x01;
    bytes[1] = 0x01;
    bytes[2] = 0x00;
    
    for (int i = 0; i < 16; i++) {
        bytes[3 + i] = _uuid[i];
    }
    
    bytes[19] = 0x00;
    bytes[20] = 0x00;
    
    NSData *data = [NSData dataWithBytes:bytes length:21];
    
    return data;
}

//通用推送命令
//命令码：16（0x10）。格式：[1][1][0x10][uuid][0x0000]
- (NSData *)get0x10DataWithUUID:(NSString *)UUID {
    NSMutableData *data = [self appversion:0x01 appID:0x01 cmd:0x10 uuid:UUID];
    Byte byte[2];
    byte[0] = 0x00;
    byte[1] = 0x00;
    
    [data appendBytes:byte length:2];
    
    return data;
}

//分类推送命令
//命令码：17（0x11）。格式：[1][1][0x11][uuid][0x0008][8字节无符号整数]
- (NSData *)get0x11DataWithUUID:(NSString *)UUID {
    NSMutableData *data = [self appversion:0x01 appID:0x01 cmd:0x11 uuid:UUID];
    Byte byte[10];
    byte[0] = 0x00;
    byte[1] = 0x08;
    
    byte[2] = 0x00;
    byte[3] = 0x00;
    byte[4] = 0x00;
    byte[5] = 0x00;
    byte[6] = 0x00;
    byte[7] = 0x00;
    byte[8] = 0x00;
    byte[9] = 0x02;
    
    [data appendBytes:byte length:10];
    
    return data;
}

//自定义信息推送命令
//命令码：32（0x20）。格式：[1][1][0x20][uuid][0x内容长度][内容字节数组]
- (NSData *)get0x20DataWithUUID:(NSString *)UUID {
    
    NSMutableData *data = [self appversion:0x01 appID:0x01 cmd:0x20 uuid:UUID];
    
    NSString *content = @"这是自定义消息最长65535";
    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger length = [contentData length];
    
    Byte byte[2];
    byte[0] = (length >> 8 ) & 0xff;
    byte[1] = (length & 0xff);
    
    [data appendBytes:byte length:2];
    [data appendData:contentData];
    
    return data;
}

- (Byte *)getByteWithUUID:(NSString *)UUID {
    
    Byte *bytes = malloc(sizeof(Byte) * 16);
    
    int j = 0;
    for(int i = 0; i < [UUID length]; i++) {
        unichar hex_char1 = [UUID characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        i++;
        
        unichar hex_char2 = [UUID characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int int_ch = int_ch1+int_ch2;
        
        bytes[j] = int_ch;  ///将转化后的数放入Byte数组里
        j++;
    }
    
    return bytes;
}

- (NSMutableData *)appversion:(Byte)appversion
                        appID:(Byte)appID
                          cmd:(Byte)cmd
                         uuid:(NSString *)uuid {
    
    Byte *bytes = malloc(sizeof(Byte) * 19);
    
    bytes[0] = appversion;
    bytes[1] = appID;
    bytes[2] = cmd;
    
    Byte *uuidByte = [self getByteWithUUID:uuid];
    for (int i = 0 ; i < 16; i++) {
        bytes[i + 3] = uuidByte[i];
    }

    NSMutableData *data = [NSMutableData dataWithBytes:bytes length:19];
    
    return data;
}



@end
